<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Cart</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
    <div class="container-fluid">
        <!-- header-keyword -->
        <div class="row" id="header">
            <div class="col-md-10">
                <input type="text" class="form-control" id="keyword" placeholder="keyword">
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-info">Search</button>
            </div>
        </div>
        <!-- nav -->
        <div class="row">
            <div class="col-md-6"></div>
            <div class="col-md-6" align="right" >
                <button type="button" id="btn_login" class="btn btn-link btn-sm">Sign in</button>
                <button type="button" id="btn_register" class="btn btn-link btn-sm">Register</button>
                <button type="button" id="btn_logout" class="btn btn-link btn-sm">Logout</button>
                <button class="btn btn-info btn-sm" type="button">
                    Cart <span class="badge" id="cartnum">0</span>
                </button>
            </div>
        </div>

        <!-- main -->
        <div class="row" id="main">
            <div-col-md-12>
                <div class="col-md-12"><h3>My Shopping Cart</h3></div>
            </div-col-md-12>
            <div class="col-md-12">
                
                <!-- myCart -->
                <div id="myCart">
                    <!-- <div class="col-md-12 ">
                        <div class="col-md-12">
                            <span>Book Name:</span>
                            <span>The Creature Choir</span>
                        </div>
                        <div class="col-md-12">
                            <span>Quantity:</span>
                            <span>1</span>
                        </div>
                        <div class="col-md-12 btns">
                            <button type="button" class="btn btn-default btn-sm">Delete</button>
                        </div>
                    </div> -->
                </div>

                <div class="col-md-12">
                    <span>Total Price: $<span id="totalprice">0</span> </span>
                </div>

                <div class="col-md-12" style="margin-top:5rem;">
                    <button type="button" class="btn btn-default btn-sm" id="btn_bcak">Back</button>
                    <button type="button" class="btn btn-default btn-sm" id="btn_check">Check out</button>
                </div>
                
            </div>
        </div>
    </div>

    <script>
        $(function(){
            //API URL
            var apiurl="http://localhost:8080";


            function islogin(){
                var currentuser=JSON.parse(sessionStorage.getItem("book_user"));
                console.log(currentuser);
                if(currentuser==undefined || currentuser==null){
                    $("#btn_login").show();
                    $("#btn_register").show();
                    $("#btn_logout").hide();
                }else{
                    $("#btn_login").hide();
                    $("#btn_register").hide();
                    $("#btn_logout").show();

                    //submit cart
                    var book_cart=JSON.parse(sessionStorage.getItem("book_cart"));
                    console.log(book_cart);
                    if(book_cart.length>0){
                        for(var i=0;i<book_cart.length;i++){
                            var params={book_id:book_cart[i].id,book_quantity:book_cart[i].Quantity};
                            $.ajax({
                                url: apiurl + "/AddBook2Cart.php",
                                type: "POST",
                                dataType: "json",
                                data:params,
                                async:false,
                                success: function (data) {
                                    
                                }
                            });
                        }
                        console.log("submit cart success");
                        //clear session
                        sessionStorage.setItem("book_cart",JSON.stringify([]));
                        
                    }
                }
                initdata();
            }

            islogin();
            

            // initdata
            function initdata(){
                var currentuser=JSON.parse(sessionStorage.getItem("book_user"));
                if(currentuser==undefined || currentuser==null){
                    var book_cart=sessionStorage.getItem("book_cart");
                    if(book_cart==null || book_cart==undefined){
                        alert("cart is null!");
                        $("#cartnum").text(0);
                        return;
                    }else{
                        book_cart=JSON.parse(book_cart);
                        inithtml(book_cart);
                    }
                }else{
                    $.ajax({
                        url: apiurl+"/Cart.php",
                        type: "POST",
                        dataType: "json",
                        success: function (data) {
                            if(data.code==0){
                                console.log(data);
                                inithtml(data.data);
                            }else{
                                alert(data.msg);
                            }
                        }
                    });
                }
                
            }

            //inithtml
            function inithtml(book_cart) {
                var myCart = $("#myCart");
                myCart.html("");
                var html = "";
                $("#cartnum").text(book_cart.length);
                var totalprice = 0;
                for (var i = 0; i < book_cart.length; i++) {
                    var book = book_cart[i];
                    var str = '<div class="col-md-12 ">' +
                        '<div class="col-md-12">' +
                        '<span>Book Name:</span>' +
                        '<span>' + book.name + '</span>' +
                        '</div>' +
                        '<div class="col-md-12">' +
                        '<span>Quantity:</span>' +
                        '<span>' + book.Quantity + '</span>' +
                        '</div>' +
                        '<div class="col-md-12 btns">' +
                        '<button type="button" val="' + book.id + '" class="btn btn-default btn-sm btn_del">Delete</button>' +
                        '</div>' +
                        '</div>';
                    html += str;

                    totalprice += ((book.price * 1) * book.Quantity);
                }
                myCart.html(html);
                $("#totalprice").text(totalprice);
            }

            //del cart
            $("#myCart").on('click','button',function(){
                var id=$(this).attr("val");
                var currentuser=JSON.parse(sessionStorage.getItem("book_user"));
                if(currentuser==undefined || currentuser==null){
                    var book_cart=JSON.parse(sessionStorage.getItem("book_cart"));
                    var index=-1;
                    for(var i=0;i<book_cart.length;i++){
                        if(book_cart[i].id==id){
                            index=i;
                            break;
                        }
                    }
                    book_cart.splice(index,1);
                    sessionStorage.setItem("book_cart",JSON.stringify(book_cart));
                }else{
                    $.ajax({
                        url: apiurl+"/DeleteBook4Cart.php",
                        type: "POST",
                        dataType: "json",
                        async:false,
                        data:{book_id:id},
                        success: function (data) {
                            if(data.code==0){
                                
                            }else{
                                alert(data.msg);
                            }
                        }
                    });
                }
                
                initdata();

            });

            //Login
            $("#btn_login").click(function(){
                window.location.href="login.html";
            });
            //Register
            $("#btn_register").click(function(){
                window.location.href="createaccount.html";
            });
            //Logout
            $("#btn_logout").click(function(){
                $.ajax({
                    url: apiurl+"/Logout.php",
                    type: "POST",
                    dataType: "json",
                    success: function (data) {
                        sessionStorage.removeItem("book_user");
                        $($("body")[0]).html('<h2 style="text-align:center;color:red;">Logging out</h2>');
                        setInterval(() => {
                            window.location.href="index.html";
                        }, 3000);
                    }
                });
            });


            $("#btn_bcak").click(function(){
                window.location.href="index.html";
            });

            $("#btn_check").click(function(){
                window.location.href="address.html";
            });
        })
    </script>
</body>
</html>